const getHolidays = (params) => {
  wx.request({
    url: 'https://timor.tech/api/holiday/year',
    data: {},
    method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
    header: {}, // 设置请求的 header
    success: function(res) {
      // success
      if (params.success) {
        params.success(res);
      }
    },
    fail: function(res) {
      // fail
      if (params.fail) {
        params.success(res);
      }
    },
    complete: function(res) {
      // complete
      if (params.complete) {
        params.success(res);
      }
    }
  })
}

const dateData = () => {
  let dataAll = [] //总日历数据
  let dataAll2 = [] //总日历数据
  let dataMonth = [] //月日历数据
  let date = new Date //当前日期
  let year = date.getFullYear() //当前年
  let week = date.getDay(); //当天星期几
  let weeks = []
  let month = date.getMonth() + 1 //当前月份
  let day = date.getDate() //当天
  let daysCount = 7 //一共显示多少天
  let dayscNow = 0 //计数器
  let monthList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] //月份列表
  let nowMonthList = [] //本年剩余月份
  for (let i = month; i < 13; i++) {
    nowMonthList.push(i)
  }
  let yearList = [year] //年份最大可能
  for (let i = 0; i < daysCount / 365 + 2; i++) {
    yearList.push(year + i + 1)
  }
  let leapYear = function(Year) { //判断是否闰年 
    if (((Year % 4) == 0) && ((Year % 100) != 0) || ((Year % 400) == 0)) {
      return (true);
    } else {
      return (false);
    }
  }
  for (let i = 0; i < yearList.length; i++) { //遍历年
    let mList
    if (yearList[i] == year) { //判断当前年份
      mList = nowMonthList //当年还剩的月份
    } else {
      mList = monthList //全年月份
    }
    for (let j = 0; j < mList.length; j++) { //循环月份
      dataMonth = [] //初始化月日历
      let t_days = [31, 28 + leapYear(yearList[i]), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] //每个月的最大天数
      let t_days_thisYear = []
      if (yearList[i] == year) { //当年的情况下
        for (let m = 0; m < nowMonthList.length; m++) { //遍历当年还剩下的月份
          t_days_thisYear.push(t_days[mList[m] - 1]) //取到还剩下的月份的每个月最大天数
        }
        t_days = t_days_thisYear
      } else {
        t_days = [31, 28 + leapYear(yearList[i]), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
      }
      for (let k = 0; k < t_days[j]; k++) { //循环每天
        dayscNow++
        let nowData
        if (dayscNow <= daysCount) { //如果计数器没满
          let days = k + 1
          if (days < 10) {
            days = "0" + days
          }
          let months = mList[j];
          if (mList[j] < 10) {
            months = "0" + mList[j];
          }
          if (yearList[i] == year && mList[j] == month) { //判断当年当月
            let days = k + day;
            if (days < 10) {
              days = "0" + days
            }
            let months = mList[j];
            if (mList[j] < 10) {
              months = "0" + mList[j];
            }

            if (k + day >= day) {
              nowData = {
                year: yearList[i],
                month: mList[j],
                day: k + day,
                date: yearList[i] + "" + months + days,
                selected: 0,
                re: yearList[i] + "-" + months + "-" + days,
              }
              dataMonth.push(nowData)
              if (k + day == day) {
                let date = new Date(yearList[i] + "/" + mList[j] + "/" + (k + day))
                let weekss = date.getDay(); //获取每个月第一天是周几
                weeks.push(weekss);
              }

              if(k + day == t_days[j])
              {
                //为每个月的最后一天时 跳出循环
                break;
              }
            }
          } else { //其他情况

            let days = k + 1
            if (days < 10) {
              days = "0" + days
            }
            let months = mList[j];
            if (mList[j] < 10) {
              months = "0" + mList[j];
            }

            nowData = { //组装自己需要的数据
              year: yearList[i],
              month: mList[j],
              day: k + 1,
              date: yearList[i] + "" + mList[j] + days,
              selected: 0,
              re: yearList[i] + "-" + mList[j] + "-" + days,
            }
            dataMonth.push(nowData)
            if (k == 0) {
              let date = new Date(yearList[i] + "/" + mList[j] + "/" + k + 1)
              let weekss = date.getDay() //获取每个月第一天是周几
              weeks.push(weekss);
            }
          }
        } else {
          //计数器满 跳出日期循环
          break;
        }
      }
      dataAll.push(dataMonth);
      //计数器满 跳出月份循环
      if (dayscNow > daysCount) {
        break;
      }
    }
    //计数器满 跳出年份循环
    if (dayscNow > daysCount) {
      break;
    }
  }
  for (let i = 0; i < dataAll.length; i++) {
    if (dataAll[i].length != 0) {
      dataAll2.push(dataAll[i]);
    }
  }
  //返回所有日期
  let allDate = {};
  allDate.date = dataAll2;
  allDate.weeks = weeks;
  return allDate;
}

const calendar = (allDate, holidays) => {
  let allDateResult = [];
  let date = new Date
  let month = '';
  let days = [];
  let day_obj = {};
  let day = '';
  let month_day = '';
  let newDays = [];
  let newMonth = [];
  let holidayName = "";
  for (let monthIndex = 0; monthIndex < allDate.length; monthIndex++) {
    month = (date.getMonth() + 1 + monthIndex).toString();
    if (month.length == 1) {
      month = '0' + month;
    }
    days = allDate[monthIndex];
    day_obj = {};
    newDays = [];
    for (let dayIndex = 0; dayIndex < days.length; dayIndex++) {
      day = days[dayIndex].day.toString();
      if (day.length == 1) {
        day = '0' + day;
      }
      month_day = month + '-' + day;
      day_obj = days[dayIndex];
      if (holidays[month_day]) {
        if (holidays[month_day].holiday) {
          day_obj.holiday = 2;
          day_obj.name = '休';
          day_obj.holidayFullName = holidays[month_day].name;
          if (holidayName === holidays[month_day].name) {
            day_obj.holidayName = "";
          } else {
            holidayName = holidays[month_day].name;
            day_obj.holidayName = holidays[month_day].name;
          }
        } else {
          day_obj.holiday = 1;
          day_obj.name = '班';
          day_obj.holidayName = '';
          day_obj.holidayFullName = '';
        }
      } else {
        day_obj.holiday = 0; //正常班
        day_obj.name = '';
        day_obj.holidayName = '';
        day_obj.holidayFullName = '';
      }
      newDays.push(day_obj);
    }
    newMonth.push(newDays);
  }
  allDateResult = newMonth;
  return allDateResult;
}

const localHolidays = (params) => {
  let holidays = {};
  let allDate = [];
  let result = [];
  let date = new Date
  allDate = dateData();
  var value = wx.getStorageSync('holidays');
  console.log(value);
  if (value) {
    let firstDay = value["01-01"].date.toString();
    let currentFirstDay = date.getFullYear().toString() + "-01-01";
    if (currentFirstDay != firstDay) {
      getHolidays({
        success: function(res) {
          holidays = res.data.holiday;
          wx.setStorage({
            key: "holidays",
            data: res.data.holiday,
          });
          console.log("重新获取节假日");
          console.log(res.data.holiday);
          result = calendar(allDate.date, holidays);
          allDate.date = result;
          if (params.success) {
            params.success(allDate);
          }
        }
      });
    } else {
      holidays = value;
      result = calendar(allDate.date, holidays);
      allDate.date = result;
      if (params.success) {
        params.success(allDate);
      }
    }
  } else {
    getHolidays({
      success: function(res) {
        holidays = res.data.holiday;
        console.log(res);
        wx.setStorage({
          key: "holidays",
          data: res.data.holiday,
        });
        result = calendar(allDate.date, holidays);
        allDate.date = result;
        if (params.success) {
          params.success(allDate);
        }
      }
    });
  }
}

module.exports = {
  localHolidays: localHolidays,
}